package com.socket.server;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author wangg
 * @date 2019/4/9 13:47
 */
class BaseReceive {
    private final Socket socket;

    protected BaseReceive(Socket socket) {


        this.socket = socket;
    }

    public String execute() throws UnsupportedEncodingException {
        InputStream in = null;
        ByteArrayOutputStream bout =new ByteArrayOutputStream();
        try {
            int c = 0;
            long start = System.currentTimeMillis();
            in = socket.getInputStream();
            while (true) {
                if(System.currentTimeMillis()-start>30*100){
                    break;
                }
                if ((c = in.available()) > 0 && c == in.available()) {
                    break;
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    break;
                }
                in = socket.getInputStream();
            }
            byte[] bytes = new byte[in.available()];
            in.read(bytes);
            bout.write(bytes,0,bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(bout.toByteArray(), StandardCharsets.UTF_8);
    }
}